package edu.xidian.onlinedocument.handler.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.xidian.onlinedocument.handler.AttributeName;
import edu.xidian.onlinedocument.handler.excpetions.custom.CustomException;
import edu.xidian.onlinedocument.service.DocumentService;
import edu.xidian.onlinedocument.service.UserService;
import edu.xidian.onlinedocument.utils.SpringUtil;
import edu.xidian.onlinedocument.views.Result;
import edu.xidian.onlinedocument.views.ResultCode;
import edu.xidian.onlinedocument.websocket.EditorSocketManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

public class WebSocketInterceptorTest implements HandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(EditorWebSocketInterceptor.class);

    private final DocumentService documentService;

    private final UserService userService;

    public WebSocketInterceptorTest() {
        documentService = SpringUtil.getBean("documentService");
        userService = SpringUtil.getBean("userService");
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response,
                                   WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        if(request instanceof ServletServerHttpRequest) {
            logger.info("requestHandshake: {} ", request.getURI());
            /*
                url: http://ip:port/websocket/test/documents/{docId}/{userId}
             */
            String temp = request.getURI().toString().split("/documents/")[1];
            Integer docId = Integer.parseInt(temp.split("/")[0]);
            Integer userId = Integer.parseInt(temp.split("/")[1]);

            // 检查用户是否有权限编辑文档
            if(!documentService.existsByDocIdAndEditorId(docId, userId)) {
                // throw new CustomException(ResultCode.DOCUMENT_IS_NOT_IN_EDITOR);
                response.setStatusCode(HttpStatus.BAD_REQUEST);
                String json = JSONObject.toJSONString(new Result(ResultCode.DOCUMENT_IS_NOT_IN_EDITOR));
                ((ServletServerHttpResponse) response).getBody().write(json.getBytes(StandardCharsets.UTF_8));
                return false;
            }
            String userNum = userService.getUserDataByUserId(userId).getUserNum();

            HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession(true);

            if(session == null) {
                return false;
            }
            attributes.put(AttributeName.CLIENT_ID, userId);
            attributes.put(AttributeName.DOC_ID, docId);
            attributes.put(AttributeName.CLIENT_NUM, userNum);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response,
                               WebSocketHandler wsHandler,
                               Exception exception) {

    }
}
